package com.example.demo.server3.tool;

public class DemoByteUtil {
    /**
     * 将低字节在前转为int，高字节在后的byte数组
     */
    public static int getInt(byte[] bArr) {
        int n = 0;
        for(int i=0;i<bArr.length&&i<4;i++){
            int left = i*8;
            n+= (bArr[i] << left);
        }
        return n;
    }

    /**
     * 将int转为低字节在前，高字节在后的byte数组
     */
    public static byte[] toBytes(int n) {
        byte[] b = new byte[4];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        b[2] = (byte) (n >> 16 & 0xff);
        b[3] = (byte) (n >> 24 & 0xff);
        return b;
    }
    /**左补0*/
    public static String leftComplement0(String s,int length){
        int nowlength = s.length();
        int difflenth = length-nowlength;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < difflenth; i++) {
            sb.append("0");
        }
        sb.append(s);
        return sb.toString();
    }
    /**int转二进制字符串,并指定位数,不足的左补0*/
    public static String intToBinary(int i,int length){
        return DemoByteUtil.leftComplement0(Integer.toBinaryString(i),length);
    }
}
